package com.fly.client1.controller;

import com.fly.client1.vo.LoginUser;
import com.fly.client1.vo.Result;
import com.fly.client1.vo.TokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LonginController
 * @Description TODO
 * @Author Fly
 * @Version
 * @Date 2020/1/7 16:00
 */
@RequestMapping()
@RestController
public class LoginController {

    @Autowired
    private RestTemplate restTemplate;


    @PostMapping("/uplogin")
    public Result<TokenResponse> login(@RequestBody LoginUser loginUser) {
        if (StringUtils.isEmpty(loginUser.getUsername()) || StringUtils.isEmpty(loginUser.getPassword())) {
            return Result.fail("登录账号或登录密码不能为空!", new TokenResponse());
        }
        StringBuilder sb = new StringBuilder("http://localhost:8080/server/oauth/token");
        sb.append("?grant_type=password");
        sb.append("&client_id=client1");
        sb.append("&client_secret=client1secret");
        sb.append("&username=").append(loginUser.getUsername());
        sb.append("&password=").append(loginUser.getPassword());
        return sendRequest(sb.toString());
    }

    /**
     * 发送请求
     *
     * @param url
     * @return
     */
    private Result<TokenResponse> sendRequest(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        ResponseEntity<TokenResponse> responseEntity = restTemplate.postForEntity(url, formEntity, TokenResponse.class);
        TokenResponse tokenResponse = responseEntity.getBody();
        return Result.ok(tokenResponse);
    }
}
